package org.ghost.http.okhttp.builder;

import org.ghost.http.okhttp.request.GetRequest;
import org.ghost.http.okhttp.request.RequestCall;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Administrator on 15/12/14.
 */
public class GetBuilder extends OkHttpRequestBuilder<GetBuilder> implements HasParamsable {
    @Override
    public RequestCall build() {
        if (params != null) {
            url = appendParams(url, params);
        }

        return new GetRequest(url, tag, params, headers, id).build();
    }

    protected String appendParams(final String url, Map<String, String> params) {
        if (url == null || params == null || params.isEmpty()) {
            return url;
        }

        if (params != null && params.size() > 0) {
            int index = 0;
            StringBuilder builder = new StringBuilder();
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    if (key != null && key.length() > 0) {
                        key = URLEncoder.encode(key, "utf-8");
                        value = URLEncoder.encode(value, "utf-8");
                        if (index == 0) {
                            String item = MessageFormat.format("{0}={1}", key, value);
                            builder.append(item);
                        } else {
                            String item = MessageFormat.format("&{0}={1}", key, value);
                            builder.append(item);
                        }
                        index++;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (url.contains("?")) {
                return url + "&" + builder.toString();
            } else {
                return url + "?" + builder.toString();
            }
        }

        return url;
    }


    @Override
    public GetBuilder params(Map<String, String> params) {
        this.params = params;
        return this;
    }

    @Override
    public GetBuilder addParams(String key, String val) {
        if (this.params == null) {
            params = new LinkedHashMap<>();
        }
        params.put(key, val);
        return this;
    }


}
